<!--
 * @Description: 手动记录查询页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="23"
        :has-add="false"
        :has-del="false"
        :has-edit="false"
        :has-cancel="false"
        :has-edit-column="true"
        @showColumn="showColumn"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" :showSelectColumn="false">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              <i class="el-icon-view"></i> 查看详情
            </el-button>
          </template>
        </template>
        <template v-slot:lesseeName="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <span>{{ row.lesseeName ? row.lesseeName : "—" }}</span>
          </template>
        </template>
        <template v-slot:collectTime="{ row }">
          <template v-if="!row.index && row.collectTime">
            {{ goTime(row.collectTime) }}
          </template>
        </template>
        <template v-slot:pictureNoList="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <el-button
              v-if="row.pictureNoList.length"
              type="success"
              @click="getpicmessage(row.pictureNoList)"
            >点击查看</el-button>
            <span v-else>暂无图片</span>
          </template>
        </template>
        <template v-slot:whetherPests="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <el-button
              v-if="row.whetherPests"
              type="warning"
              @click="showpestviewmet(row.growthProcessRecordPests.growthProcessRecordPestsId)"
            >点击处理</el-button>
            <div v-else style="color:#67C23A">无{{ farmingTypeTitles }}</div>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="'详细记录信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="批次名称:" class="w50p">
            <el-select
              v-model="formData.batchNo"
              :disabled="!canInput"
              clearable
            >
              <el-option
                v-for="(item,index) in batchList"
                :key="index"
                :label="item.batchName"
                :value="item.batchNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="记录标题:" prop="batchNo" class="w50p">
            <el-input
              v-model="formData.recordTitle"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="阶段选择:" class="w50p">
            <el-select
              v-model="formData.growthPhaseNo"
              :disabled="!canInput"
              clearable
            >
              <el-option
                v-for="(item,index) in growthPhasList"
                :key="index"
                :label="item.growthPhaseName"
                :value="item.growthPhaseNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设施选择:" prop="facilityNo" class="w50p">
            <el-select
              v-model="formData.facilityNo"
              :disabled="!canInput"
              clearable
            >
              <el-option
                v-for="(item,index) in facilityList"
                :key="index"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="生长速度" prop="batchNo" class="w50p">
            <el-autocomplete
              v-model="formData.growthSpeed"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :disabled="!canInput"
              @select="handleSelect"
            />
          </el-form-item>-->
          <el-form-item
            v-if="nowChanceStau === 'edit' || nowChanceStau === 'add'"
            label="记录图片:"
            prop="weChat"
            class="w50p"
          >
            <uploadimage
              v-if="nowsectpictureidtwo === ''"
              @getpictureid="getpictureidtwo"
            />
            <div v-else-if="nowsectpictureidtwo !== ''">图片已上传</div>
          </el-form-item>
          <el-form-item :label="'是否有' + farmingTypeTitles+':'" class="w50p">
            <el-select
              v-model="formData.whetherPests"
              :disabled="!canInput"
              clearable
            >
              <el-option
                v-for="(item,index) in whetherPestsList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests"
            :label="farmingTypeTitles + '描述：'"
            prop="weChat"
            class="w50p"
          >
            <el-input
              v-model="formData.description"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests && nowChanceStau === 'add'"
            label="病虫害图片:"
            prop="weChat"
            class="w50p"
          >
            <uploadimage
              v-if="nowsectpictureid === ''"
              @getpictureid="getpictureid"
            />
            <div v-else-if="nowsectpictureid !== ''">图片已上传</div>
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests && nowChanceStau === 'edit'"
            :label="farmingTypeTitles + '图片:'"
            prop="weChat"
            class="w50p"
          >
            <uploadimage
              v-if="nowsectpictureid === ''"
              @getpictureid="getpictureid"
            />
            <div v-else-if="nowsectpictureid !== ''">图片已上传</div>
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests"
            label="处理结果"
            prop="completionDate"
            class="w50p"
          >
            <el-input
              v-model="formData.growthProcessRecordPestsNo"
              :disabled="true"
              clearable
            />
          </el-form-item>
          <el-form-item label="记录信息:" prop="completionDate" class="w50p">
            <el-input
              v-model="formData.remark"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="物联数据" prop="completionDate" class="w50p">
            <el-date-picker
              v-model="zhdateList"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptionsone"
              @change="getdataitemlist"
            />
          </el-form-item>-->
          <el-form-item label="物联数据展示:" class="checklinesty">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0px 10px;"></div>
            <el-checkbox-group
              v-model="checkedCities"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="dataItem in dataItemList"
                :key="dataItem.dataItemId"
                :label="dataItem.dataItemName"
                :value="dataItem.dataItemName"
              >{{ dataItem.dataItemName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="图片" :visible.sync="showpicview" width="30%">
        <img
          style="width:80%;max-height:500px;margin-left:10%;"
          :src="pictviewurl"
        />
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showpicview = false">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="showpicview = false"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 病虫害处理弹窗 -->
      <el-dialog title="处理虫害" :visible.sync="showpestview" width="400px">
        <div class="diainput">
          <el-input v-model="newresult" placeholder="请填写处理结果" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showpestview = false">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="editpestmessage()"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import uploadimage from "../uploadimage/uploadimage.vue";
import facgroupreq from "@/api/user/index";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/growth-record-management/growth-record-managementtwo";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import tenantInfo from "@/api/digital-operation/tenant-manage/tenant-info/index";
import { mymixin } from "@/utils/mixin";
import { getToken } from "@/utils/auth";
import { farmingTypeTitle } from "@/utils/validate";
export default {
  name: "ManuallyRecordQuery",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot, uploadimage },
  mixins: [mymixin],
  data() {
    var farmingTypeTitles = farmingTypeTitle()
    return {
      tableColumn: [
        { prop: 'batchName', label: '批次名称' },
        { prop: 'batchNo', label: '批次号' },
        { prop: 'lesseeName', label: '种植户', slotName: 'lesseeName' },
        { prop: 'recordTitle', label: '记录标题' },
        { prop: 'collectTime', label: '记录时间', slotName: 'collectTime' },
        { prop: 'remark', label: '记录信息' },
        { prop: 'pictureNoList', label: '查看图片', slotName: 'pictureNoList' },
        { prop: 'whetherPests', label: '处理'+farmingTypeTitles, slotName: 'whetherPests' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: '100' }
      ],
      formConfig: [
        {
          label: '选择批次',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '选择设施',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilityList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' }
        }, {
          label: '选择时间',
          prop: 'date',
          type: 'daterange',
        },
      ],
      // 图片弹框
      showpicview: false,
      pictviewurl: "",
      // 虫害处理弹窗
      showpestview: false,
      farmingTypeTitles: farmingTypeTitle(),
      nowrecordid: "",
      newresult: "",

      lesseeNo: "",
      lesseeList: [],
      // 多选框相关
      checkAll: true,
      checkedCities: [],
      isIndeterminate: true,
      // 当前选中的记录图片id
      nowsectpictureidtwo: "",
      // 当前物联数据日期选择
      zhdateList: "",
      dataItemList: [],
      // 当前选中的病虫害图片id
      nowsectpictureid: "",
      // 生长阶段
      restaurants: [],
      state1: "",
      // 是否有病虫害
      whetherPestsList: [
        { name: "是", value: true },
        { name: "否", value: false }
      ],
      // 可选择批次列表
      batchList: [],
      // 可选择所有地块
      facilityList: [],
      // 获取所有生长阶段
      growthPhasList: [],
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所搜索框内容
      searchlist: {
        batchNo: "",
        facilityNo: "",
        dateList: []
      },
      pickerOptionsone: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      dialogFormVisible: false
    };
  },
  watch: {
    nowChanceStau(newval) {
      this.getselectdatalist();
      this.nowplantTypeName = "种养类别";
    }
  },
  created() {},
  mounted() {
    this.chancefarmtype(getToken("farmingTypeNo"));
    this.restaurants = this.loadAll();
  },
  methods: {
    // 处理病虫害1.展示弹窗2.点击确认调用接口
    showpestviewmet(id) {
      this.nowrecordid = id;
      this.newresult = "";
      this.showpestview = true;
    },
    editpestmessage() {
      let editparams = {
        growthProcessRecordPestsId: this.nowrecordid,
        result: this.newresult
      };
      if (this.newresult === "") {
        this.$message.error("请填写处理结果！");
      }
      nowpagereq.editpestlist(editparams).then(res => {
        if (res.code === 1) {
          this.$message.success("处理成功！");
          this.nowrecordid = "";
          this.showpestview = false;
          this.getTableDataList();
        } else {
          this.$message.error("处理失败！");
        }
      });
    },
    // 获取图片详情
    async getpicmessage(idlist) {
      let id = idlist[0];
      this.showpicview = true;
      if (id) {
        let res = await nowpagereq.growthProcessPicture(id);
        this.pictviewurl = `data:image/png;base64, ${res.data.pictureData}`;
      } else {
        this.$message.warning("暂无图片信息！");
      }
      // nowpagereq.getpicmessage(id).then(
      //   res => {
      //     console.log(res)
      //   }
      // )
    },
    // 时间戳展示正常时间
    goTime(val) {
      var timestamp4 = new Date(val);
      // 利用拼接正则等手段转化为yyyy-MM-dd HH:mm:ss 格式
      return (
        timestamp4.toLocaleDateString().replace(/\//g, "-") +
        " " +
        timestamp4.toTimeString().substr(0, 8)
      );
    },
    // 多选框选择方法
    handleCheckAllChange(val) {
      console.log(val);
      if (val) {
        this.checkedCities = this.dataItemList.map(item => {
          return item.dataitemName;
        });
      } else {
        this.checkedCities = [];
      }
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log(this.checkedCities);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.dataItemList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.dataItemList.length;
    },
    // 设置病虫害图片
    getpictureid(id) {
      this.nowsectpictureid = id;
    },
    // 设置记录图片
    getpictureidtwo(id) {
      this.nowsectpictureidtwo = id;
    },
    // 输入建议
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "一般", va: "zz" },
        { value: "快速", va: "zz" },
        { value: "缓慢", va: "zz" }
      ];
    },
    handleSelect(item) {
      console.log(this.state1);
      console.log(item);
    },

    // ----
    // 在有农业类型的页面中以此方法为获取表格方法
    chancefarmtype(e) {
      this.getselectdatalist();
      this.farmingTypeNo = e;
      // 获取表格数据
      this.getTableDataList();
    },
    // 获取下拉框数据
    async getselectdatalist() {
      // 获取所有地块
      let faciparams = {};
      if (this.nowChanceStau === "add") {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: 1
        };
      } else {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",")
            .concat([sessionStorage.parentId || ""]),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
        };
      }
      facgroupreq.getfacilityAll(faciparams).then(res => {
        this.facilityList = res.data;
        this.formConfig[1].options = res.data;
      });
      // 获取所有批次
      nowpagereq.getallbatchList().then(res => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      // 获取所有生长阶段
      nowpagereq.getallgrowthPhasList().then(res => {
        this.growthPhasList = res.data;
      });

      // 做不同的请求获取数据
      // 获取承租人下拉框
      const { data: lessee } = await tenantInfo.queryLessesByCondition();
      this.lesseeList = lessee;
      this.formConfig[2].options = lessee;
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchNo: this.searchlist.batchNo || undefined,
          lesseeNo: this.searchlist.lesseeNo || undefined,
          facilityNo: this.searchlist.facilityNo || undefined,
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          organizationNo: sessionStorage.getItem("organizationNo"),
          endTime: this.searchlist.date
            ? this.dateToFormat(this.searchlist.date[1])
            : undefined,
          startTime: this.searchlist.date
            ? this.dateToFormat(this.searchlist.date[0])
            : undefined
        }
      };
      this.entity = params.entity

      nowpagereq.getlist(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    async handleEdit(row) {
      if (row.indflag) {
        this.$message.warning("请勿选择空数据");
        return;
      }
      let res = await nowpagereq.queryByNo(row.growthProcessRecordNo);
      row = res.data;
      // this.formData = res.data;
      // // this.formData.results = row.growthProcessRecordPests.results
      // this.formData.facilityId = row.facilities[0].facilityId
      // this.facilityList = row.facilities
      // this.checkedCities = row.growthProcessRecordDataCollect.map(
      //   (item) => {
      //     return item.dataItemName
      //   }
      // )
      // // console.log(row)
      // this.dataItemList = row.growthProcessRecordDataCollect;

      this.formData = res.data;
      let pestsData = await nowpagereq.growthProcessRecordPests(
        row.growthProcessRecordPestsNo
      );
      // console.log(row)
      if (pestsData.data) {
        this.formData.result = pestsData.data.result;
        this.formData.description = pestsData.data.description;
      }
      // this.formData.facilityNo = row.facilityNoList[0];
      this.$set(this.formData, "facilityNo", res.data.facilityNoList[0]);
      // this.facilityNoList = row.facilityNoList
      this.checkedCities = row.growthProcessRecordDataCollectList.map(item => {
        return item.dataItemName;
      });
      // collectTime
      // facilities.facilityNo
      this.dataItemList = row.growthProcessRecordDataCollectList;
      this.dialogFormVisible = true;
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      let notvalue = true;
      // console.log(list)
      this.nowSelectList = list.map(item => {
        if (item.growthProcessRecordNo) {
          return item.growthProcessRecordNo;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.nowSelectList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist(this.nowSelectList).then(res => {
        if (res.code === 1) {
          this.$message.success("删除成功！");
          this.getTableDataList();
        } else {
          this.$message.error("删除失败！");
        }
      });
    },
    save() {
      // -----保存状态判断-----
      if (this.nowChanceStau === "edit") {
        let editparams = {
          recordTitle: this.formData.recordTitle,
          growthProcessRecordNo: this.formData.growthProcessRecordNo,
          growthPhaseNo: this.formData.growthPhaseNo,
          batchNo: this.formData.batchNo,
          // facilityId: this.formData.facilityId,
          growthSpeed: this.formData.growthSpeed,
          whetherPests: this.formData.whetherPests
        };
        if (this.formData.facilityId) {
          editparams.facilityIdList = [this.formData.facilityId];
          // delete editparams.facilityId
        }
        if (this.nowsectpictureidtwo !== "") {
          editparams.pictureIdList = [this.nowsectpictureidtwo];
        }
        if (this.formData.whetherPests === true) {
          if (this.nowsectpictureid !== "") {
            editparams.petPictureId = this.nowsectpictureid;
          }
          editparams.description = this.formData.description;
        }
        if (this.checkAll) {
          editparams.growthProcessRecordDataCollectList = this.dataItemList;
        } else {
          // 根据选中的名字一个找出对应的数据-zz
        }
        nowpagereq.editlist(editparams).then(res => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.getTableDataList();
          } else {
            this.$message.error("修改失败！");
          }
        });
      } else if (this.nowChanceStau === "add") {
        // 新增接口
        let zhparams = {
          ...this.formData,
          collectTime: "1630292026000"
        };
        if (this.formData.facilityId) {
          zhparams.facilityIdList = [this.formData.facilityId];
          delete zhparams.facilityId;
        }
        if (this.nowsectpictureidtwo !== "") {
          zhparams.pictureIdList = [this.nowsectpictureidtwo];
        }
        if (this.formData.whetherPests === true) {
          zhparams.petPictureId = this.nowsectpictureid;
        }
        if (this.checkAll) {
          zhparams.growthProcessRecordDataCollectList = this.dataItemList;
        } else {
          // 根据选中的名字一个找出对应的数据-zz
        }
        nowpagereq.addlist(zhparams).then(res => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.getTableDataList();
          } else {
            this.$message.error("修改失败！");
          }
        });
      }
    },
    getdataitemlist() {
      let params = {
        date: this.dateToFormat(this.zhdateList),
        facilityId: this.formData.facilityId
      };
      nowpagereq.getalldataitembydateList(params).then(res => {
        this.dataItemList = res.data;
        this.dataItemList.forEach(item => {
          this.checkedCities.push(item.dataItemName);
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
.checklinesty {
  width: 100% !important;
  // background-color: #85ce61;
}
::v-deep .el-checkbox {
  .el-checkbox__label {
    // color: initial;
    display: inline-block;
    // flex-direction: column;
  }
}
.diainput {
  // background-color: aqua;
  ::v-deep .el-input__inner {
    color: #006e91 !important;
  }
}
</style>
